<?php
namespace App\Task;

use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;


class CreateViewTableTask
{
    protected LoggerInterface $logger;

    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'CreateViewTable');
    }

    public function execute()
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('default');

        try {
            $this->logger->info(date('Y-m-d H:i:s') . '------------------------创建对应的数据库表');

            $nextMonth = strtotime("+1 month", time());
            $month =  date('Ym',$nextMonth);
            $monthLogKey = 'user_view_month_table'.$month;
            //判断是否有创建当月的数据库
            $monthVal = $redis->get($monthLogKey);

            if(empty($monthVal)){
                $this->logger->info(date('Y-m-d H:i:s') . '------------------------开始创建对应的数据库');

                $sql = 'CREATE TABLE data_user_viewing_log_'.$month.' LIKE data_user_viewing_log';

                $this->logger->info('创建的sql语句',[$sql]);
                $result = Db::insert($sql);
                if($result){
                    $this->logger->info('创建的用户记录表成功');
                    $redis->set($monthLogKey,'1');
                    $this->logger->info('设置创建表的redis');
                }
            }
        }catch (\Exception $e){
            $this->logger->error('请求|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------创建对应的数据库表结束');
    }
}